package edu.kit.aifb.ldsbench.out2;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import org.openrdf.model.Statement;
import org.openrdf.rio.RDFHandlerException;
import org.openrdf.rio.ntriples.NTriplesWriter;

public class FileOutput implements IGeneratorOutput {

	private static int counter = 0;
	
	private String dir;
	private File file;
	private Writer writer;
	private NTriplesWriter ntriple;
	
	public FileOutput(String path){
		try {
			File file = new File(path);
			file.delete();
			file.createNewFile();
			this.file = file;
			this.writer = new FileWriter(file);
			this.ntriple = new NTriplesWriter(this.writer);
			try {
				this.ntriple.startRDF();
			} catch (RDFHandlerException e) {
				e.printStackTrace();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public FileOutput(String directory, String name){
		try {
			File dir = new File(directory);
			if(!dir.exists()){
				dir.createNewFile();
			}
						
			File file = new File(directory + name + counter++);
			file.delete();
			file.createNewFile();
			this.writer = new FileWriter(file);
			this.ntriple = new NTriplesWriter(this.writer);
			try {
				this.ntriple.startRDF();
			} catch (RDFHandlerException e) {
				e.printStackTrace();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	/** {@inheritDoc }*/
	@Override
	public void generateOutput(String output) {
		try {
			this.writer.write(output);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/** {@inheritDoc }*/
	@Override
	public void close() {
		try {
			this.writer.flush();
			this.ntriple.endRDF();
			this.writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (RDFHandlerException e) {
			e.printStackTrace();
		}
		this.ntriple = null;
		this.writer = null;
	}

	/** {@inheritDoc }*/
	@Override
	public void startEvent(String prefix) {
		// prefixes
		try {
			this.writer.write(prefix);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/** {@inheritDoc }*/
	@Override
	public void endEvent() {
		try {
			this.writer.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void generateOutput(Statement s) {
		if(s.getSubject() == null){
			System.out.println("Subject is null");
		}if(s.getPredicate() == null){
			System.out.println("Predicate is null");
		}if(s.getObject() == null){
			System.out.println("Object is null");
		}
		try {
			this.ntriple.handleStatement(s);
			this.writer.flush();
		} catch (RDFHandlerException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public String getDir(){
		return this.dir;
	}
	
	public String getPath(){
		return this.file.getAbsolutePath();
	}

}
